package zcw.com.lib_leet_code;

import java.util.Arrays;

/**
 * Created by 朱城委 on 2021/7/15.<br><br>
 *
 * 第三大的数
 */
public class Topic414 {

    public static void main(String[] args) {
        Topic414 instance = new Topic414();

        int[] array = new int[] {3,2,1};
        System.out.println(instance.thirdMax(array));

        array = new int[] {2,2,3,1};
        System.out.println(instance.thirdMax(array));

        array = new int[] {1,2};
        System.out.println(instance.thirdMax(array));
    }

        public int thirdMax(int[] nums) {
            long value1 = Long.MIN_VALUE;
            long value2 = Long.MIN_VALUE;
            long value3 = Long.MIN_VALUE;

            for(int value : nums) {
                if(value <= value3 || value == value1 || value == value2) {
                    continue;
                }

                if(value > value1) {
                    value3 = value2;
                    value2 = value1;
                    value1 = value;
                    continue;
                }

                if(value > value2) {
                    value3 = value2;
                    value2 = value;
                    continue;
                }

                value3 = value;
            }

            if(value3 == Long.MIN_VALUE) {
                return (int) value1;
            }
            else {
                return (int) value3;
            }
        }

    public int thirdMax2(int[] nums) {
        Arrays.sort(nums);

        int counter = 0;
        for(int i = nums.length - 1; i > 0; i--) {
            if(nums[i] != nums[i - 1]) {
                counter++;
                if(counter == 2) {
                    return nums[i - 1];
                }
            }
        }

        return nums[nums.length - 1];
    }
}
